<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="计算机,网络,通讯协议," />





  <link rel="alternate" href="/atom.xml" title="Ewan's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="互联网协议入门每天重复搬砖的动作,发现很多底层的基础只是都有点忘了…补一下喽,这里参照阮一峰的博客梳理一下互联网的核心是一系列的协议,总称为”互联网协议”(Internet Protocol Suite).它们对电脑如何连接和组网,做出了详尽的规定.理解了这些协议,就理解了互联网的原理.">
<meta name="keywords" content="计算机,网络,通讯协议">
<meta property="og:type" content="article">
<meta property="og:title" content="互联网协议总结(一)">
<meta property="og:url" content="http://www.iooeo.com/2016/12/13/互联网协议总结-一/index.html">
<meta property="og:site_name" content="Ewan&#39;s Blog">
<meta property="og:description" content="互联网协议入门每天重复搬砖的动作,发现很多底层的基础只是都有点忘了…补一下喽,这里参照阮一峰的博客梳理一下互联网的核心是一系列的协议,总称为”互联网协议”(Internet Protocol Suite).它们对电脑如何连接和组网,做出了详尽的规定.理解了这些协议,就理解了互联网的原理.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052902.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052903.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052904.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052905.jpg">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052906.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052907.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052914.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052908.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052909.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052910.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052911.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052912.png">
<meta property="og:image" content="http://image.beekka.com/blog/201205/bg2012052913.png">
<meta property="og:updated_time" content="2016-12-14T06:37:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="互联网协议总结(一)">
<meta name="twitter:description" content="互联网协议入门每天重复搬砖的动作,发现很多底层的基础只是都有点忘了…补一下喽,这里参照阮一峰的博客梳理一下互联网的核心是一系列的协议,总称为”互联网协议”(Internet Protocol Suite).它们对电脑如何连接和组网,做出了详尽的规定.理解了这些协议,就理解了互联网的原理.">
<meta name="twitter:image" content="http://image.beekka.com/blog/201205/bg2012052902.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.iooeo.com/2016/12/13/互联网协议总结-一/"/>





  <title>互联网协议总结(一) | Ewan's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cea7ef9cbfe59c235bbe4bb0db874f5b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ewan's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Ewan's Blog | 杨依园技术博客 | 专注于PHP，涉及MySQL，Linux，Web，Nginx，Apache，Phalcon，Laravel，Redis，PostgreSql，Composer，Beanstalkd，Swoole</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-php">
          <a href="/categories/PHP/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-paper-plane"></i> <br />
            
            php
          </a>
        </li>
      
        
        <li class="menu-item menu-item-yii">
          <a href="/categories/PHP/Yii2/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-star"></i> <br />
            
            Yii2
          </a>
        </li>
      
        
        <li class="menu-item menu-item-swoole">
          <a href="/categories/PHP/Swoole/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />
            
            swoole
          </a>
        </li>
      
        
        <li class="menu-item menu-item-python">
          <a href="/categories/python/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-space-shuttle"></i> <br />
            
            python
          </a>
        </li>
      
        
        <li class="menu-item menu-item-awesome">
          <a href="/categories/awesome/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-dashboard"></i> <br />
            
            awesome
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.iooeo.com/2016/12/13/互联网协议总结-一/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ewan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ewan's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">互联网协议总结(一)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-12-13T11:41:29+08:00">
                2016-12-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/计算机/" itemprop="url" rel="index">
                    <span itemprop="name">计算机</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2016/12/13/互联网协议总结-一/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2016/12/13/互联网协议总结-一/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2016/12/13/互联网协议总结-一/" class="leancloud_visitors" data-flag-title="互联网协议总结(一)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="互联网协议入门"><a href="#互联网协议入门" class="headerlink" title="互联网协议入门"></a>互联网协议入门</h2><p>每天重复搬砖的动作,发现很多底层的基础只是都有点忘了…补一下喽,这里参照<a href="http://www.ruanyifeng.com" target="_blank" rel="noopener">阮一峰</a>的博客梳理一下<br>互联网的核心是一系列的协议,总称为”互联网协议”(Internet Protocol Suite).它们对电脑如何连接和组网,做出了详尽的规定.理解了这些协议,就理解了互联网的原理.<br><a id="more"></a></p>
<h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>1.1 五层模型</p>
<blockquote>
<p>互联网的实现，分成好几层。每一层都有自己的功能，就像建筑物一样，每一层都靠下一层支持。<br>用户接触到的，只是最上面的一层，根本没有感觉到下面的层。要理解互联网，必须从最下层开始，自下而上理解每一层的功能。<br>如何分层有不同的模型，有的模型分七层，有的分四层。个人觉得把互联网分成五层，比较容易解释。<br><img src="http://image.beekka.com/blog/201205/bg2012052902.png" alt="互联网实现-h250"><br>如图所示,越往下面的层,越靠近硬件;越往上面的层,越靠近用户.</p>
</blockquote>
<p>1.2 层与协议</p>
<blockquote>
<p>每一层都是为了完成一种功能.为了实现这些功能,就需要大家都遵守共同的规则.<br>大家都遵守的规则,就叫做”协议”(protocol).<br>互联网的每一层都定义了很多协议.这些协议的总称,就叫做”互联网协议”(Internet Protocol Suite).它是互联网的核心.</p>
</blockquote>
<h3 id="实体层-Physical-Layer"><a href="#实体层-Physical-Layer" class="headerlink" title="实体层 Physical Layer"></a>实体层 Physical Layer</h3><blockquote>
<p>从最底下的一层开始.<br>计算机要组网,当然是先把电脑连接起来,可以用光缆,电缆,双绞线,无线电波等方式.<br><img src="http://image.beekka.com/blog/201205/bg2012052903.png" alt="计算机组网"><br>这就叫做”实体层”,他就是把电脑连接起来的物理手段.它主要规定了网络的一些电气特性,作用是负责传送0和1的电信号.</p>
</blockquote>
<h3 id="链接层-Link-Layer"><a href="#链接层-Link-Layer" class="headerlink" title="链接层 Link Layer"></a>链接层 Link Layer</h3><p>3.1 定义</p>
<blockquote>
<p>单纯的0和1没有任何意义,必须规定解读方式:多少个电信号算一组?每个信号位有什么意义?<br>这就是”链接层”的功能,它在”实体层”的上方,确定了0和1的分组方式.</p>
</blockquote>
<p>3.2 以太网协议</p>
<blockquote>
<p>早期的时候,每家公司都有自己的电信号分组方式.逐渐的一种叫做”以太网”(Ethernet)的协议,占据了主导地位.<br>以太网规定,一组电信号构成一个数据包,叫做”帧”(Frame).每一帧分成两个部分:标头(head)和数据(data).<br><img src="http://image.beekka.com/blog/201205/bg2012052904.png" alt="帧"><br>“标头”包含数据包的一些说明项,比如发送者,接受者,数据类型等等;”数据”则是数据包的具体内容.<br>“标头”的长度,固定为18字节.”数据”长度,最短为46字节,最长为1500字节.因此,整个”帧”最短为64字节,最长为1518字节,如果数据很长,就必须分割成多个”帧”进行发送.</p>
</blockquote>
<p>3.3 MAC地址</p>
<blockquote>
<p>上面提到，以太网数据包的”标头”,包含了发送者和接受者的信息,那么,发送者和接受者是如何标识呢?<br>以太网规定,连入网络的所有设备,都必须具有”网卡”接口.数据包必须是从一块网卡,传送到另一块网卡.网卡的地址,就是数据包的发送地址和接收地址,这叫做MAC地址.<br><img src="http://image.beekka.com/blog/201205/bg2012052905.jpg" alt="网卡"><br>每块网卡出厂的时候,都有一个全世界独一无二的MAC地址,长度是48个二进制位,通常用12个十六进制数表示.<br><img src="http://image.beekka.com/blog/201205/bg2012052906.png" alt="网卡"><br>前6个十六进制数是厂商编号,后6个是该厂商的网卡流水号.有了MAC地址,就可以定位网卡和数据包的路径了.</p>
</blockquote>
<p>3.4 广播</p>
<blockquote>
<p>定义地址只是第一步,后面还有更多的步骤.<br>首先,一块网卡怎么会知道另一块网卡的MAC地址?<br>回答是有一种ARP协议,可以解决这个问题.这个留到后面介绍,这里只需要知道,以太网数据包必须知道接收方的MAC地址,然后才能发送.<br>其次,就算有了MAC地址,系统怎样才能把数据包准确的发送到接收方?<br>回答是以太网采用了一种很”原始”的方式,它不是把数据包准确送到接收方,而是向本网络内所有计算机发送,让每台计算机自己判断,是否为接受方.<br><img src="http://image.beekka.com/blog/201205/bg2012052907.png" alt="数据包发送"><br>上图中,1号计算机向2号计算机发送一个数据包,同一个子网络的3号,4号,5号计算机都会收到这个包.它们读取到这个包的”标头”,找到接收方的MAC地址,然后与自身的MAC地址相比较,如果两者相同,就接收这个包,做进一步处理,否则就丢弃这个包.这种发送方式就叫做”广播”(broadcasting).<br>有了这个数据包的定义,网卡的MAC地址,广播的发送方式,”连接层”就可以在多台计算机之间传送数据了.</p>
</blockquote>
<h3 id="网络层-Network-Layer"><a href="#网络层-Network-Layer" class="headerlink" title="网络层 Network Layer"></a>网络层 Network Layer</h3><p>4.1 网络层的由来</p>
<blockquote>
<p>以太网协议,依靠MAC地址发送数据.理论上,单单依靠MAC地址,上海的网卡就可以找到洛杉矶的网卡了,技术上是可以实现的.<br>但是,这样做有一个重大的缺点,以太网采用广播的发送方式发送数据包,所有成员人手一”包”,不仅效率低,而且局限在发送者所在的子网络.这就是说,如果两台计算机不在同一个子网络,广播是传不过去的.这种设计是合理的,否则互联网上每一台计算机都会收到所有的”包”,那会引起灾难.<br>互联网是无数子网络共同组成的一个巨型网络,很难想象上海和洛杉矶的电脑会在同一个子网络,这几乎是不可能的.<br><img src="http://image.beekka.com/blog/201205/bg2012052914.png" alt="Internet"><br>因此,必须找到一种方法,能够区分哪些MAC地址属于同一个子网络,哪些不是.如果是同一子网络,就采用广播的方式发送,否则就采用”路由”的方式发送.(“路由”的意思,是指如何向不同的子网络发送数据包,这是一个很大的主题,本文不涉及.)遗憾的是,MAC地址本身无法做到这一点,它只与厂商有关,与所出网络无关.<br>这就导致了”网络层”的诞生,它的作用是引进一套新的地址,使得我们能区分不同的计算机是否属于同一个自网络.这套地址就叫做”网络地址”,简称”网址”.<br>于是,”网络层”出现以后,每台计算机有了两种地址,一种是MAC地址,另一种是网络地址.两种地址之间没有任何联系,MAC地址是绑定在网卡上的,网络地址则是管理员分配的,它们只是随机组合在一起.<br>网络地址帮助我们确定计算机所在的子网络,MAC地址则将数据包发送到该子网络中的没押镖网卡.因此,从逻辑上可以推断,必定是先处理网络地址,然后再处理MAC地址.</p>
</blockquote>
<p>4.2 IP协议</p>
<blockquote>
<p>规定网络地址的协议,叫做IP协议.它所定义的地址,就被称为IP地址.<br>目前,广泛采用的IP协议第四版,简称IPv4.这个版本规定,网络地址由32个二进制位组成.<br><img src="http://image.beekka.com/blog/201205/bg2012052908.png" alt="IP"><br>习惯上,我们分成4段的十进制数表示IP地址,从0.0.0.0一直到255.255.255.255.<br>互联网上每一台计算机,都会分配到一个IP地址.这个地址分成两部分,前一部分代表网络,后一部分代表主机.比如,IP地址172.16.254.1,这是一个32位的地址,假定它的网络部分是前24位(172.16.254),那么主机部分就是后8位(最后一个1).处于同一子网络的计算机,它们的IP地址的网络部分必定是相同的,也就是说172.16.254.2应该与172.16.254.1处于同一个子网络.<br>但是,问题在于单单从IP地址,我们无法判断网络部分.还是以172.16.254.1为例,它的网络部分,到底是前24位,还是前16位,甚至是前28位,从IP地址上是看不出来的.<br>那么.怎样才能从IP地址,判断两台计算机是否属于同一个子网络呐?这就是要用到另一个参数”子网掩码”(subnet mask).<br>所谓”子网掩码”,就是表示子网络特征的一个参数.它在形式上等同于IP地址,也就是一个32位的二进制数字,他的网络部分全部为1,主机部分全部为0.比如,IP地址172.16.254.1,如果已知网络部分是前24位,主机部分是后8位,那么子网掩码就是11111111.11111111.11111111.00000000,写成十进制就是255.255.255.0<br>知道”子网掩码”,我们就能判断,任意两个IP地址是否处在同一个子网络.方法是将两个IP地址与子网掩码分别进行AND运算(两个数位都为1,运行结果为1,否则为0),然后比较结果是否相同,如果是的话,就表明它们在同一个子网络中,否则就不是.<br>比如,一直IP地址172.16.254.1和172.16.254.233的子网掩码都是255.255.255.0,请问它们是否在同一个子网络?两者与子网掩码分别进行AND运算,结果都是172.16.254.0,因此它们在同一个子网络.<br>总结一下,IP协议的作用主要有两个,一个是为每一台计算机分配IP地址,另一个是确定哪些IP地址在同一个子网络.</p>
</blockquote>
<p>4.3 IP数据包</p>
<blockquote>
<p>根据IP协议发送的数据,就叫做IP数据包.不难想象,其中必定包括IP信息.<br>但是前面说过,以太网数据包值包含MAC地址,并没有IP地址的栏位.那么是否需要修改数据包定义,再添加一个栏位呐?<br>回答是不需要,我们可以把IP数据包直接放进意外网数据包的”数据”部分,因此完全不用修改以太网的规格.这就是互联网分层结构的好处:上层的变动完全不涉及下层的结构.<br>具体来说,IP数据包也分为”标头”和”数据”两部分.<br><img src="http://image.beekka.com/blog/201205/bg2012052909.png" alt="IP数据包"><br>“标头”部分主要包括版本,长度,IP地址等信息,”数据”部分则是IP数据包的具体内容,它放进以太网数据包后,以太网数据包就变成了下面这样.<br><img src="http://image.beekka.com/blog/201205/bg2012052910.png" alt="以太网数据包"><br>IP数据包的”标头”部分的长度为20~60字节,真个数据包的总长度为65535字节.因此,理论上,一个IP数据包的”数据”部分,最长为65515字节.前面说过,以太网数据包的”数据”部分,最长只有1500字节,因此,IP数据包超过了1500字节,它就需要分割成几个以太网数据包,发开发送了.</p>
</blockquote>
<p>4.4 ARP协议</p>
<blockquote>
<p>关于”网络层”,还有最后一点需要说明.<br>因为IP数据包是放在以太网数据包里发送的,所以我们必须同时知道两个地址,一个是对方的MAC地址,另一个是对方的IP地址.通常情况下,对方的IP地址是已知的(后文会解释),但是我们不知道它的MAC地址.<br>所以,我们需要一种机制,能够从IP地址得到MAC地址.<br>这里又可以分成两种情况.第一种情况,如果两台主机不在同一个子网络,那么事实上没有办法得到对方的MAC地址,只能把数据包传送到两个子网络连接处的”网关”(gateway),让网关去处理.<br>第二种情况,如果两台主机在同一个子网络,那么我们可以用ARP协议,得到对方的MAC地址.ARP协议也是发出一个数据包(包含在以太网数据包中),其中包含它所要查询主机的IP地址,在对方的MAC地址这一栏,填的是FF:FF:FF:FF:FF:FF,表示这是一个”广播”地址.它所在子网络的每一台主机,都会收到这个数据包,从中取出IP地址,与自身的IP地址进行比较.如果两者相同,都做出回复,向对方报告自己的MAC地址,否则就丢弃这个包.<br>总之,有了ARP协议之后,我们就可以得到同一个子网络内的主机MAC地址,可以把数据包发送到任意一台主机之上了.</p>
</blockquote>
<h3 id="传输层-Transport-Layer"><a href="#传输层-Transport-Layer" class="headerlink" title="传输层 Transport Layer"></a>传输层 Transport Layer</h3><p>5.1 传输层的由来</p>
<blockquote>
<p>有了MAC地址和IP地址,我们已经可以在互联网上任意两台主机上建立通信.<br>接下来的问题是,同一台主机上有许多程序都需要用到网络,比如,你一边浏览网页,一边与朋友在线聊天.当一个数据包从互联网上发来的时候,你怎么知道,它是表示网页的内容,还是表示在线聊天的内容?<br>也就是说,我们还需要一个参数,表示这个数据包到底供哪个程序(进程)使用.这个参数就叫做”端口”(port)，它其实是每一个使用网卡的程序的编号.每个数据包都发到主机的特定端口,所以不同的程序就能取到自己所需要的数据.<br>“端口”是0到65535之间的一个整数,正好16个二进制位.0到1023的端口被系统占用,用户只能选用大于1023的端口.不管是浏览网页还是在线聊天,应用程序会随机选用一个端口,然后与服务器的相应端口联系.<br>“传输层”的功能,就是建立”端口到端口”的通信.相比之下,”网络层”的功能是建立”主机到主机”的通信.只要确定主机和端口,我们就能实现程序之间的交流.因此,Unix系统就把主机+端口,叫做”套接字”(socket).有了它,就可以进行网络应用程序开发了.</p>
</blockquote>
<p>5.2 UDP协议</p>
<blockquote>
<p>现在,我们必须在数据包中加入端口信息,这就需要新的协议.最简单的实现叫做UDP协议,它的格式几乎就是在数据前面,加上端口号.<br>UDP数据包也,是由”标头”和”数据”两部分组成.<br><img src="http://image.beekka.com/blog/201205/bg2012052911.png" alt="UDP数据包"><br>“标头”部分主要定义了发出端口和接收端口,”数据”部分就是具体的内容.然后,把整个UDP数据包放入IP数据包的”数据”部分,而前面说过,IP数据包又是放在以太网数据包之中的,所以整个以太网数据包现在变成了下面这样:<br><img src="http://image.beekka.com/blog/201205/bg2012052912.png" alt="以太网数据包"><br>UDP数据包非常简单,”标头”部分一共只有8个字节,总长度不超过65535字节,正好放进一个IP数据包.</p>
</blockquote>
<p>5.3 TCP协议</p>
<blockquote>
<p>UDP协议的优点是比较简单,容易实现,但是缺点是可靠性较差,一旦数据包发出,无法知道对方是否收到.<br>为了解决这个问题,提高网络可靠性,TCP协议就诞生了.这个协议非常复杂,但可以近似认为,它就是有确认机制的UDP协议,每发出一个数据包都要求确认.如果有一个数据包遗失,就收不到确认,发出方就知道有必要重发这个数据包了.<br>因此,TCP协议能够确保数据不会遗失.它的缺点是过程复杂,实现困难,消耗较多的资源.<br>TCP数据包和UDP数据包一样,都是内嵌在IP数据包的”数据”部分.TCP数据包没有长度限制,理论上可以无限长,但是为了保证网络的效率,通常TCP数据包的长度不会超过IP数据包的长度,以确保单个TCP数据包不必再分割.</p>
</blockquote>
<h3 id="应用层-Application-Layer"><a href="#应用层-Application-Layer" class="headerlink" title="应用层 Application Layer"></a>应用层 Application Layer</h3><blockquote>
<p>应用程序收到”传输层”的数据,接下来就要进行解读.由于互联网是开放架构,数据来源五花八门,必须事先规定好格式,否则根本无法解读.<br>“应用层”的作用,就是规定应用程序的数据格式.<br>举例来说,TCP协议可以为各种各样的程序传递数据,比如Email,WWW,FTP等等.那么,必须有不同协议规定电子邮件,网页,FTP数据的格式.这些应用程序协议就构成了”应用层”.<br>这是最高的一层,直接面对用户.它的数据就放在TCP数据包的”数据”部分.因此,现在的以太网的数据包就变成下面这样.<br><img src="http://image.beekka.com/blog/201205/bg2012052913.png" alt="以太网数据包"><br>至此,整个互联网的五层结构,自下而上全部讲完了.这是从系统的角度,解释互联网是如何构成的.</p>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div align="center">
      
        <div class="copyright">
        <p><span>
        <b>本文地址：</b><a href="/2016/12/13/互联网协议总结-一/" title="互联网协议总结(一)">http://www.iooeo.com/2016/12/13/互联网协议总结-一/</a><br/><b>转载请注明出处，谢谢！</b>
        </span></p>
        </div>
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="http://ogpq2zwg5.bkt.clouddn.com/WechatIMG15.jpeg" alt="Ewan WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="http://ogpq2zwg5.bkt.clouddn.com/WechatIMG16.jpeg" alt="Ewan Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/计算机/" rel="tag"># 计算机</a>
          
            <a href="/tags/网络/" rel="tag"># 网络</a>
          
            <a href="/tags/通讯协议/" rel="tag"># 通讯协议</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/12/12/git删除已提交的文件或文件夹/" rel="next" title="git删除已提交的文件或文件夹">
                <i class="fa fa-chevron-left"></i> git删除已提交的文件或文件夹
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/31/Yii2 创建应用/" rel="prev" title="Yii2 创建应用">
                Yii2 创建应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Ewan" />
          <p class="site-author-name" itemprop="name">Ewan</p>
           
              <p class="site-description motion-element" itemprop="description">The more effort ,the more lucky</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">138</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">40</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://resume.iooeo.com/" target="_blank" title="Resume">
                  
                    <i class="fa fa-fw fa-handshake-o"></i>
                  
                  Resume
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2120563685" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/yangyiyuan" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:654846126@qq.com" target="_blank" title="Email">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                  Email
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.firedata.cn/" target="_blank" title="Company">
                  
                    <i class="fa fa-fw fa-users"></i>
                  
                  Company
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://game.iooeo.com/" target="_blank" title="MyGame">
                  
                    <i class="fa fa-fw fa-gamepad"></i>
                  
                  MyGame
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.firedata.cn/" title="在职-意静科技" target="_blank">在职-意静科技</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.xd.com/" title="曾供职-心动网络" target="_blank">曾供职-心动网络</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.mobase.cn/" title="曾供职-翼成科技" target="_blank">曾供职-翼成科技</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.blueberrytech.cn/base/" title="曾供职-蓝莓盈动" target="_blank">曾供职-蓝莓盈动</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://old.tumiaoya.com/" title="白宝冰-博客" target="_blank">白宝冰-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liuxiaojia.cc/" title="刘佳-博客" target="_blank">刘佳-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.pythondev.org" title="曹帅军-博客" target="_blank">曹帅军-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.dannisi.xin" title="李丹-博客" target="_blank">李丹-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://xcx.iooeo.com/" title="Cow's Love 工作室" target="_blank">Cow's Love 工作室</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#互联网协议入门"><span class="nav-number">1.</span> <span class="nav-text"><a href="#&#x4E92;&#x8054;&#x7F51;&#x534F;&#x8BAE;&#x5165;&#x95E8;" class="headerlink" title="&#x4E92;&#x8054;&#x7F51;&#x534F;&#x8BAE;&#x5165;&#x95E8;"></a>&#x4E92;&#x8054;&#x7F51;&#x534F;&#x8BAE;&#x5165;&#x95E8;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#概述"><span class="nav-number">1.1.</span> <span class="nav-text"><a href="#&#x6982;&#x8FF0;" class="headerlink" title="&#x6982;&#x8FF0;"></a>&#x6982;&#x8FF0;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实体层-Physical-Layer"><span class="nav-number">1.2.</span> <span class="nav-text"><a href="#&#x5B9E;&#x4F53;&#x5C42;-Physical-Layer" class="headerlink" title="&#x5B9E;&#x4F53;&#x5C42; Physical Layer"></a>&#x5B9E;&#x4F53;&#x5C42; Physical Layer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#链接层-Link-Layer"><span class="nav-number">1.3.</span> <span class="nav-text"><a href="#&#x94FE;&#x63A5;&#x5C42;-Link-Layer" class="headerlink" title="&#x94FE;&#x63A5;&#x5C42; Link Layer"></a>&#x94FE;&#x63A5;&#x5C42; Link Layer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络层-Network-Layer"><span class="nav-number">1.4.</span> <span class="nav-text"><a href="#&#x7F51;&#x7EDC;&#x5C42;-Network-Layer" class="headerlink" title="&#x7F51;&#x7EDC;&#x5C42; Network Layer"></a>&#x7F51;&#x7EDC;&#x5C42; Network Layer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#传输层-Transport-Layer"><span class="nav-number">1.5.</span> <span class="nav-text"><a href="#&#x4F20;&#x8F93;&#x5C42;-Transport-Layer" class="headerlink" title="&#x4F20;&#x8F93;&#x5C42; Transport Layer"></a>&#x4F20;&#x8F93;&#x5C42; Transport Layer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#应用层-Application-Layer"><span class="nav-number">1.6.</span> <span class="nav-text"><a href="#&#x5E94;&#x7528;&#x5C42;-Application-Layer" class="headerlink" title="&#x5E94;&#x7528;&#x5C42; Application Layer"></a>&#x5E94;&#x7528;&#x5C42; Application Layer</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright" >
  
  &copy;  2013 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ewan</span>
  &nbsp;
  <span id="busuanzi_container_site_uv">
      <i class="fa fa-user-md"></i>
      本站访客数:<span id="busuanzi_value_site_pv"></span>
    </span>
</div>


<div class="powered-by">
  <span class="links-of-author-item">
    <a href="http://www.miitbeian.gov.cn/" target="_blank" title="备案号">
    沪ICP备17032516号-1
    </a>
  </span>
</div>

<div class="powered-by">
  <span class="links-of-author-item">
    <a href="https://github.com/yangyiyuan" target="_blank" title="GitHub">
    <i class="fa fa-github-alt"></i>
    GitHub
    </a>
  </span>
</div>

<div class="theme-info">
  <span class="links-of-author-item">
    <a href="http://www.iooeo.com/about/" target="_blank" title="杨依园">
    <i class="fa fa-fw fa-hand-o-right"></i>
    做一个有思想的开发者---杨依园
    </a>
  </span>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyt8r7gzu';
      var conf = 'a4830425918b568a51dfe3d835fd90db';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("ilQJ7Pnw4P9y1I1cQlaOoggK-gzGzoHsz", "uwSCLmjySIQiXUJHwkhc5XdT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script></body>
</html>
